<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useServerStore } from '../stores/serverStore'
import { useAuthStore } from '../stores/auth'
import api from '../api'

const router = useRouter()
const serverStore = useServerStore()
const authStore = useAuthStore()

// 搜索和筛选状态
const searchQuery = ref('')
const selectedType = ref<'all' | 'official' | 'community' | 'huawei'>('all')
const selectedCategory = ref('')
const currentPage = ref(1)
const pageSize = ref(12)
const showSubmitModal = ref(false)

// 新增分类和标签列表
const categories = ref<any[]>([])
const allTags = ref<any[]>([])

// 获取分类和标签数据
const fetchCategoriesAndTags = async () => {
  try {
    const [categoriesResponse, tagsResponse] = await Promise.all([
      api.servers.getCategories(),
      api.servers.getTags()
    ])
    categories.value = categoriesResponse.data
    allTags.value = tagsResponse.data
  } catch (error) {
    console.error('获取分类和标签失败:', error)
  }
}

// 新服务器表单
const newServer = ref({
  name: '',
  description: '',
  status: true,
  category: '',
  category_name: '',
  github: '',
  tags: [] as string[],
  newTag: ''
})

// 获取服务器数据
onMounted(() => {
  serverStore.fetchServers()
  fetchCategoriesAndTags()
})

// 监听分类选择变化
watch(selectedCategory, (newCategory) => {
  if (newCategory) {
    // 如果选择了分类，使用API获取该分类下的服务器
    fetchServersByCategory(newCategory)
  } else {
    // 如果没有选择分类，获取所有服务器
    serverStore.fetchServers()
  }
})

// 监听搜索关键词变化
watch(searchQuery, () => {
  // 重置到第一页
  currentPage.value = 1
})

// 监听类型筛选变化
watch(selectedType, () => {
  // 重置到第一页
  currentPage.value = 1
})

// 根据分类名称获取服务器
const fetchServersByCategory = async (categoryName: string) => {
  try {
    serverStore.isLoading = true
    const response = await api.servers.getByCategory(categoryName)
    serverStore.servers = response.data
  } catch (error) {
    console.error('根据分类获取服务器失败:', error)
  } finally {
    serverStore.isLoading = false
  }
}

// 筛选服务器
const filteredServers = computed(() => {
  return serverStore.servers.filter(server => {
    const matchesSearch = server.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      server.description.toLowerCase().includes(searchQuery.value.toLowerCase())
    
    const matchesType = selectedType.value === 'all' || 
      (selectedType.value === 'huawei' ? server.source === 'huawei' : 
      (server.is_official ? selectedType.value === 'official' : selectedType.value === 'community'))
    
    const matchesCategory = selectedCategory.value === '' || 
      server.category_name === selectedCategory.value
    
    return matchesSearch && matchesType && matchesCategory
  })
})

// 分页服务器
const paginatedServers = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredServers.value.slice(start, end)
})

// 总页数
const totalPages = computed(() => {
  return Math.ceil(filteredServers.value.length / pageSize.value)
})

// 分页按钮显示计算
const displayedPageNumbers = computed(() => {
  const total = totalPages.value
  const current = currentPage.value
  const displayRange = 5 // 显示的页数按钮数量
  
  if (total <= displayRange) {
    // 总页数少于显示范围，显示所有页码
    return Array.from({ length: total }, (_, i) => i + 1)
  }
  
  // 显示当前页附近的页码，两边各显示(displayRange-3)/2个页码
  const sideItems = Math.floor((displayRange - 3) / 2)
  let startPage = Math.max(current - sideItems, 1)
  let endPage = Math.min(startPage + displayRange - 3, total)
  
  if (endPage - startPage < displayRange - 3) {
    startPage = Math.max(endPage - (displayRange - 3), 1)
  }
  
  const pages = []
  
  // 始终显示第一页
  if (startPage > 1) {
    pages.push(1)
    // 如果第一页和起始页之间有间隔，显示省略号
    if (startPage > 2) {
      pages.push('...')
    }
  }
  
  // 添加中间页码
  for (let i = startPage; i <= endPage; i++) {
    pages.push(i)
  }
  
  // 始终显示最后一页
  if (endPage < total) {
    // 如果结束页和最后一页之间有间隔，显示省略号
    if (endPage < total - 1) {
      pages.push('...')
    }
    pages.push(total)
  }
  
  return pages
})

// 页面控制
const goToPage = (page: number | string) => {
  if (typeof page === 'number') {
    currentPage.value = page
    window.scrollTo({ top: 0, behavior: 'smooth' })
  }
}

const goToNextPage = () => {
  if (currentPage.value < totalPages.value) {
    goToPage(currentPage.value + 1)
  }
}

const goToPrevPage = () => {
  if (currentPage.value > 1) {
    goToPage(currentPage.value - 1)
  }
}

// 导航到服务器详情
const navigateToServerDetail = (serverId: string) => {
  router.push({ name: 'server-detail', params: { id: serverId } })
}

// 提交服务器表单处理
const addTagToNewServer = () => {
  if (newServer.value.newTag && !newServer.value.tags.includes(newServer.value.newTag)) {
    newServer.value.tags.push(newServer.value.newTag)
    newServer.value.newTag = ''
  }
}

const removeTagFromNewServer = (tag: string) => {
  const index = newServer.value.tags.indexOf(tag)
  if (index !== -1) {
    newServer.value.tags.splice(index, 1)
  }
}

// 选择分类时设置selectedCategory
const selectFilterCategory = (categoryName: string) => {
  if (selectedCategory.value === categoryName) {
    selectedCategory.value = '' // 如果再次点击相同分类则取消选择
  } else {
    selectedCategory.value = categoryName
  }
  currentPage.value = 1 // 重置到第一页
}

// 重置表单
const resetNewServerForm = () => {
  newServer.value = {
    name: '',
    description: '',
    status: true,
    category: '',
    category_name: '',
    github: '',
    tags: [],
    newTag: ''
  }
}

const submitNewServer = () => {
  // 添加时间戳
  const serverData = {
    ...newServer.value,
    id: `server-${Date.now()}`,
    created_at: new Date().toISOString(),
    updated_at: new Date().toISOString(),
    owner: authStore.user?.id
  }
  
  // 移除临时字段 - 修复lint错误
  const { newTag, ...dataToSubmit } = serverData;
  
  // 调用添加服务器的方法
  serverStore.addServer(dataToSubmit)
  
  // 重置表单并关闭模态框
  resetNewServerForm()
  showSubmitModal.value = false
}

// 登出
const logout = () => {
  authStore.logout()
  router.push('/login')
}
</script>

<template>
  <div class="min-h-screen">
    <!-- 导航栏 -->
    <nav class="bg-white shadow-lg sticky top-0 z-10">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex justify-between h-16">
          <div class="flex">
            <div class="flex-shrink-0 flex items-center">
              <h1 class="text-2xl font-bold text-gray-900">MCP Server <span class="text-blue-600">导航</span></h1>
            </div>
            
            <!-- 分类导航 -->
            <div class="hidden sm:ml-8 sm:flex sm:items-center">
              <div class="flex space-x-4">
                <button 
                  @click="selectedType = 'all'" 
                  :class="[
                    'px-3 py-2 rounded-md text-sm font-medium',
                    selectedType === 'all' 
                      ? 'bg-blue-600 text-white' 
                      : 'text-gray-700 hover:text-gray-900 hover:bg-gray-100'
                  ]"
                >
                  全部
                </button>
                <button 
                  @click="selectedType = 'community'" 
                  :class="[
                    'px-3 py-2 rounded-md text-sm font-medium',
                    selectedType === 'community' 
                      ? 'bg-blue-600 text-white' 
                      : 'text-gray-700 hover:text-gray-900 hover:bg-gray-100'
                  ]"
                >
                  社区
                </button>
                <button 
                  @click="selectedType = 'huawei'" 
                  :class="[
                    'px-3 py-2 rounded-md text-sm font-medium',
                    selectedType === 'huawei' 
                      ? 'bg-blue-600 text-white' 
                      : 'text-gray-700 hover:text-gray-900 hover:bg-gray-100'
                  ]"
                >
                  华为
                </button>
              </div>
            </div>
          </div>
          
          <!-- 用户信息和提交按钮 -->
          <div class="flex items-center space-x-4">
            <button 
              v-if="authStore.isAuthenticated"
              @click="showSubmitModal = true"
              class="bg-green-500 hover:bg-green-600 text-white font-bold py-2 px-4 rounded-md flex items-center"
            >
              <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-1" viewBox="0 0 20 20" fill="currentColor">
                <path fill-rule="evenodd" d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z" clip-rule="evenodd" />
              </svg>
              提交服务器
            </button>
            
            <div v-if="authStore.isAuthenticated" class="relative ml-3">
              <div class="flex items-center space-x-3">
                <span class="text-gray-700">{{ authStore.user?.username }}</span>
                <router-link
                  to="/latest-servers" 
                  class="text-blue-500 hover:text-blue-700 font-medium"
                >
                  最新提交
                </router-link>
                <button 
                  @click="logout"
                  class="text-gray-500 hover:text-gray-700 font-medium"
                >
                  登出
                </button>
              </div>
            </div>
            
            <router-link 
              v-else 
              to="/login"
              class="text-gray-500 hover:text-gray-700 font-medium"
            >
              登录
            </router-link>
          </div>
        </div>
      </div>
    </nav>

    <!-- 主要内容 -->
    <main class="page-container">
      <!-- 顶部信息 -->
      <div class="text-center mb-8">
        <h2 class="text-3xl font-bold text-gray-900 mb-2">Model Context Protocol 服务器导航</h2>
        <p class="text-lg text-gray-600">发现、探索和连接各种MCP服务器资源</p>
      </div>

      <!-- 搜索和筛选 -->
      <div class="filter-card">
        <div class="flex flex-col sm:flex-row gap-4 mb-4">
          <div class="search-container">
            <input
              type="text"
              v-model="searchQuery"
              placeholder="搜索 MCP Server..."
              class="search-input"
            />
            <div class="search-icon">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                <path fill-rule="evenodd" d="M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z" clip-rule="evenodd" />
              </svg>
            </div>
          </div>
          <select
            v-model="selectedType"
            class="input"
          >
            <option value="all">全部类型</option>
            <option value="official">官方</option>
            <option value="community">社区</option>
            <option value="huawei">华为</option>
          </select>
        </div>
        
        <!-- 分类筛选 -->
        <div v-if="categories.length > 0" class="mb-4">
          <div class="mb-2 text-sm font-medium text-gray-700">按分类筛选:</div>
          <div class="filter-tags">
            <button
              @click="selectedCategory = ''; serverStore.fetchServers()"
              :class="[
                'filter-tag',
                selectedCategory === '' ? 'filter-tag-active' : 'filter-tag-inactive'
              ]"
            >
              全部
            </button>
            <button
              v-for="category in categories"
              :key="category.id"
              @click="selectFilterCategory(category.name)"
              :class="[
                'filter-tag',
                selectedCategory === category.name ? 'filter-tag-active' : 'filter-tag-inactive'
              ]"
            >
              {{ category.name }} ({{ category.count }})
            </button>
          </div>
        </div>
      </div>
      
      <!-- 加载状态 -->
      <div v-if="serverStore.isLoading" class="flex justify-center my-8">
        <div class="spinner"></div>
      </div>

      <!-- 错误提示 -->
      <div v-else-if="serverStore.error" class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 my-4 rounded">
        <p>{{ serverStore.error }}</p>
      </div>

      <!-- 无结果提示 -->
      <div v-else-if="filteredServers.length === 0" class="text-center py-12">
        <div class="text-5xl mb-4">🔍</div>
        <h3 class="text-xl font-medium text-gray-900 mb-2">未找到匹配的服务器</h3>
        <p class="text-gray-600">尝试使用不同的搜索词或清除筛选条件</p>
      </div>

      <!-- 服务器列表 -->
      <div v-else>
        <div class="mb-4 text-sm text-gray-600">
          显示 {{ filteredServers.length }} 个结果中的 {{ Math.min((currentPage - 1) * pageSize + 1, filteredServers.length) }} - {{ Math.min(currentPage * pageSize, filteredServers.length) }}
        </div>
        
        <div class="server-grid">
          <div
            v-for="server in paginatedServers"
            :key="server.id"
            class="server-card"
            @click="navigateToServerDetail(server.id)"
          >
            <div class="server-card-content">
              <div class="server-header">
                <h3 class="server-title">
                  {{ server.name }}
                </h3>
                <span
                  :class="[
                    'tag',
                    server.source === 'huawei' ? 'tag-danger' : 
                    server.type === 'official' ? 'tag-success' : 'tag-primary'
                  ]"
                >
                  {{ server.source === 'huawei' ? '华为' : 
                     server.type === 'official' ? '官方' : '社区' }}
                </span>
              </div>
              <p class="server-description">{{ server.description }}</p>
              <div class="server-tags">
                <span
                  v-for="tag in server.tags.slice(0, 3)"
                  :key="tag"
                  class="tag tag-secondary"
                >
                  {{ tag }}
                </span>
                <span
                  v-if="server.tags.length > 3"
                  class="tag tag-secondary"
                >
                  +{{ server.tags.length - 3 }}
                </span>
              </div>
              <div class="server-footer">
                <span class="server-link">
                  查看详情 →
                </span>
              </div>
            </div>
          </div>
        </div>

        <!-- 分页控制 -->
        <div v-if="totalPages > 1" class="pagination">
          <nav class="flex items-center space-x-1">
            <button 
              @click="goToPrevPage"
              :disabled="currentPage === 1"
              :class="[
                'pagination-button',
                currentPage === 1 ? 'pagination-disabled' : 'pagination-inactive'
              ]"
            >
              上一页
            </button>
            
            <template v-for="(page, index) in displayedPageNumbers" :key="index">
              <span v-if="page === '...'" class="pagination-ellipsis">...</span>
              <button
                v-else
                @click="goToPage(page)"
                :class="[
                  'pagination-button',
                  currentPage === page ? 'pagination-active' : 'pagination-inactive'
                ]"
              >
                {{ page }}
              </button>
            </template>
            
            <button
              @click="goToNextPage"
              :disabled="currentPage === totalPages"
              :class="[
                'pagination-button',
                currentPage === totalPages ? 'pagination-disabled' : 'pagination-inactive'
              ]"
            >
              下一页
            </button>
          </nav>
        </div>
      </div>
    </main>

    <!-- 页脚 -->
    <footer class="bg-gray-800 text-white py-8 mt-12">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex flex-col md:flex-row justify-between items-center">
          <div class="mb-4 md:mb-0">
            <h2 class="text-xl font-bold">MCP Server 导航</h2>
            <p class="text-gray-400">Model Context Protocol 服务器资源集合</p>
          </div>
          <div class="flex space-x-4">
            <a href="https://mcp.so" target="_blank" class="text-gray-300 hover:text-white">
              官方网站
            </a>
            <a href="https://github.com" target="_blank" class="text-gray-300 hover:text-white">
              GitHub
            </a>
          </div>
        </div>
      </div>
    </footer>
    
    <!-- 提交新服务器模态框 -->
    <div v-if="showSubmitModal" class="fixed inset-0 flex items-center justify-center z-50">
      <div class="fixed inset-0 bg-black opacity-50"></div>
      <div class="bg-white rounded-lg shadow-xl p-6 w-full max-w-2xl z-10 max-h-[90vh] overflow-y-auto">
        <h2 class="text-2xl font-bold mb-6 text-gray-800 border-b pb-3">添加新服务器</h2>
        
        <form @submit.prevent="submitNewServer" class="space-y-6">
          <!-- 基本信息 -->
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label class="block text-gray-700 font-medium mb-2">服务器名称 <span class="text-red-500">*</span></label>
              <input 
                v-model="newServer.name" 
                type="text" 
                class="w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                required
              >
            </div>
            
            <div>
              <label class="block text-gray-700 font-medium mb-2">状态</label>
              <div class="flex items-center mt-3">
                <input 
                  id="statusActive" 
                  v-model="newServer.status" 
                  type="checkbox" 
                  class="h-4 w-4 text-blue-600 focus:ring-blue-500"
                >
                <label for="statusActive" class="ml-2 text-gray-700">活跃</label>
              </div>
            </div>
          </div>
          
          <!-- 源码地址 -->
          <div>
            <label class="block text-gray-700 font-medium mb-2">源码地址 <span class="text-red-500">*</span></label>
            <input 
              v-model="newServer.github" 
              type="url" 
              class="w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              required
              placeholder="https://github.com/username/repository"
            >
          </div>
          
          <!-- 分类选择 - 改为下拉框 -->
          <div>
            <label class="block text-gray-700 font-medium mb-2">分类 <span class="text-red-500">*</span></label>
            <select
              v-model="newServer.category" 
              class="w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              required
              @change="newServer.category_name = newServer.category"
            >
              <option value="" disabled>请选择分类</option>
              <option 
                v-for="category in categories" 
                :key="category.id" 
                :value="category.name"
              >
                {{ category.name }}
              </option>
            </select>
          </div>
          
          <!-- 标签 -->
          <div>
            <label class="block text-gray-700 font-medium mb-2">标签</label>
            <div class="flex items-center space-x-2 mb-2">
              <input 
                v-model="newServer.newTag" 
                type="text" 
                class="flex-grow px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                placeholder="添加标签..."
              >
              <button 
                type="button" 
                @click="addTagToNewServer"
                class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
              >
                添加
              </button>
            </div>
            
            <!-- 已选标签 -->
            <div class="flex flex-wrap gap-2">
              <div 
                v-for="(tag, index) in newServer.tags" 
                :key="index"
                class="px-3 py-1 bg-blue-100 text-blue-800 rounded-full flex items-center"
              >
                {{ tag }}
                <button 
                  type="button" 
                  @click="removeTagFromNewServer(tag)"
                  class="ml-2 text-blue-600 hover:text-blue-800"
                >
                  &times;
                </button>
              </div>
            </div>
          </div>
          
          <!-- 描述 -->
          <div>
            <label class="block text-gray-700 font-medium mb-2">描述 <span class="text-red-500">*</span></label>
            <textarea 
              v-model="newServer.description" 
              class="w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 h-32"
              required
            ></textarea>
          </div>
          
          <!-- 提交和取消按钮 -->
          <div class="flex justify-end space-x-4">
            <button 
              type="button" 
              @click="showSubmitModal = false"
              class="px-6 py-2 bg-gray-300 text-gray-700 rounded-lg hover:bg-gray-400"
            >
              取消
            </button>
            <button 
              type="submit"
              class="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
            >
              提交
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<style scoped>
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.tag-danger {
  @apply bg-red-100 text-red-800;
}

.page-container {
  @apply max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6;
}

.filter-card {
  @apply bg-white p-4 rounded-lg shadow-md mb-6;
}

.search-container {
  @apply relative flex-1;
}

.search-input {
  @apply block w-full pr-10 border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500;
}

.search-icon {
  @apply absolute inset-y-0 right-0 pr-3 flex items-center pointer-events-none text-gray-400;
}

.input {
  @apply block w-full sm:w-40 pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-blue-500 focus:border-blue-500 rounded-md;
}

.filter-tags {
  @apply flex flex-wrap gap-2;
}

.filter-tag {
  @apply inline-flex items-center px-3 py-1 rounded-md text-sm font-medium;
}

.filter-tag-active {
  @apply bg-blue-100 text-blue-800;
}

.filter-tag-inactive {
  @apply bg-gray-100 text-gray-800 hover:bg-gray-200;
}

.server-grid {
  @apply grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4;
}

.server-card {
  @apply bg-white rounded-lg shadow hover:shadow-md transition-shadow duration-200 overflow-hidden cursor-pointer border border-gray-200;
}

.server-card-content {
  @apply p-4;
}

.server-header {
  @apply flex justify-between items-start mb-2;
}

.server-title {
  @apply text-lg font-bold text-gray-900 line-clamp-2;
}

.tag {
  @apply inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium;
}

.tag-primary {
  @apply bg-blue-100 text-blue-800;
}

.tag-success {
  @apply bg-green-100 text-green-800;
}

.tag-secondary {
  @apply bg-gray-100 text-gray-800;
}

.server-description {
  @apply text-sm text-gray-600 mb-4 line-clamp-2;
}

.server-tags {
  @apply flex flex-wrap gap-1.5 mb-3;
}

.server-footer {
  @apply flex justify-between items-center pt-2 border-t border-gray-100;
}

.server-link {
  @apply text-sm font-medium text-blue-600 hover:text-blue-500;
}

.pagination {
  @apply flex justify-center mt-8;
}

.pagination-button {
  @apply inline-flex items-center px-4 py-2 mx-1 text-sm font-medium rounded-md;
}

.pagination-active {
  @apply bg-blue-600 text-white;
}

.pagination-inactive {
  @apply bg-white text-gray-700 hover:bg-gray-50;
}

.pagination-disabled {
  @apply bg-gray-100 text-gray-400 cursor-not-allowed;
}

.pagination-ellipsis {
  @apply inline-flex items-center px-2 mx-1 text-sm font-medium text-gray-700;
}

.spinner {
  @apply animate-spin rounded-full h-12 w-12 border-t-4 border-b-4 border-blue-500;
}
</style> 